package cn.mdmbct.douyin.common.http.okhttp;


import cn.mdmbct.douyin.common.config.HttpConfig;
import cn.mdmbct.douyin.common.http.HttpExecutor;
import cn.mdmbct.douyin.common.http.HttpExecutorFactory;
import okhttp3.OkHttpClient;

import java.util.concurrent.TimeUnit;

/**
 * @author mdmbct  mdmbct@outlook.com
 * @date 2021/4/16 22:13
 * @modified mdmbct
 * @since 1.0
 */
public class OkHttpExecutorFactory implements HttpExecutorFactory {

    private static volatile OkHttpExecutor okHttpExecutor;

    /**
     * 单例
     */
    @Override
    public HttpExecutor createHttpExecutor(HttpConfig httpConfig) {
        return create(httpConfig);
    }

    /**
     * 创建单例的OkHttpExecutor 使用默认的HttpConfig{@link HttpConfig}
     * @return 单例的OkHttpExecutor
     */
    private static OkHttpExecutor instance() {
        if (okHttpExecutor == null) {
            synchronized (OkHttpExecutor.class) {
                if (okHttpExecutor == null) {
                    okHttpExecutor = create(new HttpConfig());
                }
            }
        }
        return okHttpExecutor;
    }

    /**
     * 每次创建的都是一个新的OkhttpExecutor实例
     * @param httpConfig httpConfig
     * @return 新的OkhttpExecutor实例
     */
    private static OkHttpExecutor create(HttpConfig httpConfig) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .addInterceptor(new RetryInterceptor(httpConfig.getMaxRetry()))
                .callTimeout(httpConfig.getResponseTimeout(), TimeUnit.MILLISECONDS)
                .connectTimeout(httpConfig.getConnectTimeout(), TimeUnit.MILLISECONDS);
        return new OkHttpExecutor(builder.build());
    }
}
